package cn.zero.letaomallspringboot.controller;

import cn.zero.letaomallspringboot.Constant.ResultCode;
import cn.zero.letaomallspringboot.common.PageResult;
import cn.zero.letaomallspringboot.common.Result;
import cn.zero.letaomallspringboot.entity.Order;
import cn.zero.letaomallspringboot.service.IOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Tag(name = "订单管理", description = "订单的查询、创建、更新、删除等操作")
@RestController
@RequestMapping("/order")
public class OrderController {
    private final IOrderService orderService;
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    public OrderController(IOrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 分页查询订单列表
     */
    @Operation(summary = "分页查询订单列表", description = "支持按订单ID、支付方式、订单状态筛选")
    @GetMapping("/list")
    public Result<PageResult<Order>> orderList(
            // 4. 参数说明：标记每个参数的含义和默认值
            @Parameter(description = "页码（默认1）", required = false, example = "1")
            @RequestParam(defaultValue = "1") int page,
            @Parameter(description = "每页条数（默认10）", required = false, example = "10")
            @RequestParam(defaultValue = "10") int size,
            @Parameter(description = "订单ID", required = false)
            @RequestParam(required = false) Long orderId,
            @Parameter(description = "支付方式（支付宝/微信支付/货到付款）", required = false)
            @RequestParam(required = false) String paymentMethod,
            @Parameter(description = "订单状态（待发货/已完成/待付款/配送中/已取消）", required = false)
            @RequestParam(required = false) String orderStatus) {

        Map<String, Object> params = new HashMap<>();
        params.put("page", page);
        params.put("size", size);

        if (orderId != null) {
            params.put("orderId", orderId);
        }
        if (paymentMethod != null && !paymentMethod.trim().isEmpty()) {
            params.put("paymentMethod", paymentMethod.trim());
        }
        if (orderStatus != null && !orderStatus.trim().isEmpty()) {
            params.put("orderStatus", orderStatus.trim());
        }

        PageResult<Order> pageResult = orderService.orderList(params);
        return Result.success(pageResult);
    }

    /**
     * 根据ID查询订单详情
     */
    @GetMapping("/{id}")
    public Result<Order> getOrder(@PathVariable Long id) {
        logger.info("查询订单详情: {}", id);
        Order order = orderService.getOrderById(id);
        if (order == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND); // 订单不存在
        }
        return Result.success(order);
    }

    /**
     * 创建新订单
     */
    @PostMapping
    public Result<Order> addOrder(@RequestBody Order order) {
        logger.info("创建新订单: {}", order);

        // 简单参数校验
        if (order.getGoodId() == null) {
            return Result.fail(ResultCode.PARAM_MISS, "商品ID不能为空");
        }
        if (order.getAmount() == null || order.getAmount() <= 0) {
            return Result.fail(ResultCode.PARAM_MISS, "商品数量必须大于0");
        }
        if (order.getTotalPrice() == null) {
            return Result.fail(ResultCode.PARAM_MISS, "订单金额不能为空");
        }

        boolean success = orderService.createOrder(order);
        if (!success) {
            return Result.fail(ResultCode.ORDER_INSERT_FAIL); // 订单创建失败
        }
        return Result.success(order, "订单创建成功");
    }

    /**
     * 更新订单信息
     */
    @PutMapping("/{id}")
    public Result<Order> updateOrder(@PathVariable Long id, @RequestBody Order order) {
        logger.info("更新订单: {},{}", id, order);

        // 验证订单是否存在
        Order existingOrder = orderService.getOrderById(id);
        if (existingOrder == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND);
        }

        order.setOrderId(id); // 设置ID以确保更新正确记录
        boolean success = orderService.updateOrder(order);
        if (!success) {
            return Result.fail(ResultCode.ORDER_UPDATE_FAIL); // 订单更新失败
        }
        return Result.success(order, "订单更新成功");
    }

    /**
     * 根据ID删除订单
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteOrder(@PathVariable Long id) {
        logger.info("删除订单: {}", id);

        Order order = orderService.getOrderById(id);
        if (order == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND); // 订单不存在
        }

        boolean success = orderService.deleteOrder(id);
        if (!success) {
            return Result.fail(ResultCode.ORDER_DELETE_FAIL); // 订单删除失败
        }
        return Result.success(null, "订单删除成功");
    }

    /**
     * 批量删除订单
     */
    @DeleteMapping("/batch")
    public Result<Void> batchDeleteOrder(@RequestBody List<Long> ids) {
        logger.info("批量删除订单: {}", ids);

        if (ids == null || ids.isEmpty()) {
            return Result.fail(ResultCode.PARAM_MISS, "请选择要删除的订单");
        }

        boolean success = orderService.batchDeleteOrder(ids);
        if (!success) {
            return Result.fail(ResultCode.ORDER_BATCH_DELETE_FAIL); // 订单批量删除失败
        }
        return Result.success(null, "订单批量删除成功");
    }

    /**
     * 更新订单状态
     */
    @PatchMapping("/{id}/status")
    public Result<Order> updateOrderStatus(
            @PathVariable Long id,
            @RequestParam String orderStatus) {
        logger.info("更新订单状态: {} -> {}", id, orderStatus);

        Order order = orderService.getOrderById(id);
        if (order == null) {
            return Result.fail(ResultCode.ORDER_NOT_FOUND);
        }

        boolean success = orderService.updateOrderStatus(id, orderStatus);
        if (!success) {
            return Result.fail(ResultCode.ORDER_UPDATE_FAIL, "订单状态更新失败");
        }

        order.setOrderStatus(orderStatus);
        return Result.success(order, "订单状态更新成功");
    }
}